import tkinter
from tkinter import *
import tkinter.messagebox
from register import *
from mainpage import *
from socket import *

def login_ui():
    # 创建应用程序窗口
    root = tkinter.Tk()
    root.title("欢迎来到娱乐世界")
    varName = StringVar()
    varName.set('')
    varPwd = StringVar()
    varPwd.set('')
    
    # 设置窗口大小
    root.geometry('500x500+300+150')
    # 创建一个图片管理类
    photo = tkinter.PhotoImage(file="image/hello.png")  # file：t图片路径
    imgLabel = tkinter.Label(root, image=photo, compound=tkinter.CENTER, bg="#BBB990")  # 把图片整合到标签类中
    imgLabel.pack(side=tkinter.LEFT)  # 自动对齐
    imgLabel.place(x=0, y=0)

    # 创建标签
    labelName = tkinter.Label(root, text='用户名:', justify=tkinter.RIGHT,width=80, font=("微软雅黑", 14), bg='#BBB990')
    # 将标签放到窗口上
    labelName.place(x=100, y=250, width=90, height=20)

    def test():
        if entryName.get() == '':
            tkinter.messagebox.showerror(title='warner', message='用户名不能为空')

    def test1():
        if entryPwd.get() == '':
            tkinter.messagebox.showerror(title='warner', message='minnjdbvkvnkvalvbkdlv不能为空')
    # 创建文本框，同时设置关联的变量
    entryName = tkinter.Entry(root, width=100, textvariable=varName,
                              validate="focusout",bg='#E0E0C4', validatecommand=test)

    entryName.place(x=200, y=240, width=200, height=35)
    labelPwd = tkinter.Label(
        root, text='密 码:', justify=tkinter.RIGHT, width=80, font=("微软雅黑", 14), bg="#BBB990")
    labelPwd.place(x=100, y=300, width=90, height=20)
    # 创建密码文本框
    entryPwd = tkinter.Entry(root, show='*', width=100,bg='#E0E0C4', textvariable=varPwd)
    entryPwd.place(x=200, y=290, width=200, height=35)

    def cancel():
        print("已退出该系统！")
        root.destroy()

    def login_mainpage_open():
        HOST = "0.0.0.0"
        PORT = 8002
        s = socket()
        s.connect((HOST,PORT))
        name = entryName.get()
        passwd = entryPwd.get()
        msg = "L {} {}".format(name,passwd)
        s.send(msg.encode())
        data = s.recv(128).decode()
        if data == 'OK':
            tkinter.messagebox.showinfo(title='游戏世界', message='登录成功！')
            print("登录成功！")
            print("已进入主页面！")
            mainpage(root,s,name)
        else:
            tkinter.messagebox.showinfo(title='游戏世界', message='用户名或者密码不正确！')
            print("用户名或密码不正确")
            s.close()

    buttonOk = tkinter.Button(root, text='登录', bg="#ADA758",
                              font=("微软雅黑", 14),command=login_mainpage_open)
    buttonOk.place(x=130, y=400, width=75, height=35)
    buttonOk = tkinter.Button(root, text='注册', bg="#ADA758",
                              font=("微软雅黑", 14),command=register)
    buttonOk.place(x=225, y=400, width=75, height=35)

    buttonCancel = tkinter.Button(root, text='退出', bg="#ADA758",
                                  font=("微软雅黑", 14), command=cancel)
    buttonCancel.place(x=320, y=400, width=75, height=35)
    # 启动消息循环
    root.mainloop()

if __name__ == "__main__":
    login_ui()